require(["common", "jQuery", "coAjax", "queryString", "href", "hash_routie"], function(jSouper, $, coAjax, QueryString, href, hash_routie) {

	var theme_packages = [{
		name: "蔚蓝",
		data: "http://o2oimg.qiniudn.com/FqLRgwu9Jsq1asM-6XN_JoeV_daa-|-true-|-true-|-true-|-#0058D1-|-#970078-|-#f5f5fa",
	}, {
		name: "翠绿",
		data: "http://o2oimg.qiniudn.com/Fo9MK-lRRuZnkbV15Kclfm1cAG-l-|-true-|-true-|-true-|-#3fa357-|-#00c4ff-|-#ffffff"
	}, {
		name: "琉璃",
		data: "http://o2oimg.qiniudn.com/FkS5X8GNXJiqE5Dvnsd7DNu74V6y-|-false-|-true-|-false-|-#7a7a91-|-#4cb332-|-#f5f5f5"
	}];
	jSouper.forEach(theme_packages, function(theme_package) {
		theme_package.config = _themepackage_parse(theme_package.data);
	});
	App.set("$Cache.themepackages", theme_packages);


	//开启预览
	hash_routie.on("themepackage", function() {
		App.set("ispreview", true);

		var bus_config = App.get("bus_loginer.config") || {};
		var bus_theme_stringify = _themepackage_stringify(bus_config);
		console.log(bus_theme_stringify);
		jSouper.forEach(theme_packages, function(theme_package) {
			if (theme_package.data == bus_theme_stringify) {
				App.set("$Cache.themepackage.stringifyData", theme_package.name);
				return false;
			}
		});
	});

	function _themepackage_stringify(bus_config) {
		var color_theme = bus_config.theme || {};
		var stringify = [bus_config.using_bg_img || "", !!bus_config.is_bg_img_blur, !!bus_config.is_use_bg_img, !!bus_config.is_bg_img_alpha,
			color_theme.first_color || "",
			color_theme.second_color || "",
			color_theme.font_color || ""
		].join("-|-");
		return stringify;
	};


	function _themepackage_parse(themepackage_string) {
		var info = themepackage_string.split("-|-");
		var result = {
			using_bg_img: info.shift() || "",
			is_bg_img_blur: info.shift() == "true",
			is_use_bg_img: info.shift() == "true",
			is_bg_img_alpha: info.shift() == "true",
			theme: {
				first_color: info.shift() || "",
				second_color: info.shift() || "",
				font_color: info.shift() || "",
			}
		}
		return result;
	};

	function _upload_config(cb) {
		coAjax.put(appConfig.bus.set_config_url, {
			mix_data: App.get("bus_loginer.config"),
			keys: ["using_bg_img", "is_bg_img_blur", "is_use_bg_img", "is_bg_img_alpha", "theme"]
		}, function(result) {
			var bus_info = result.result;
			App.set("bus_loginer", bus_info);
			cb && cb();
		}, function(errorCode, xhr, errorMsg) {
			alert("error", errorMsg);
		});
	}

	App.set("$Event.themepackage.change_theme", function(e, vm) {
		var data = vm.get("data");
		var config = _themepackage_parse(data);
		for (var key in config) {
			if (config.hasOwnProperty(key)) {
				console.log("bus_loginer.config." + key, config[key]);
				App.set("bus_loginer.config." + key, config[key]);
			}
		}
	});
	App.set("$Event.themepackage.upload_config", function() {
		_upload_config(function() {
			alert("success", "修改成功")
		});
	});
});